import { ref, reactive } from 'vue';
import useLoginStore from '@/stores/login';
import { captchaSent, cellphoneCheck, loginCellphone } from '@/modules/request';
import { debounce } from '@/modules/characteristic';
import { InputListLoginInter, InputPlaceholderEnum } from '@/types/login';

export default function useLoginRegistry() {
	/** login仓库 */
	const loginStore = useLoginStore();
	// input数据
	const inputPwdMaxLength = 18;
	const inputList = reactive<InputListLoginInter[]>([
		{
			type: 'tel',
			placeholder: InputPlaceholderEnum.phone,
			maxlength: 11,
			'placeholder-style': 'color: #636363;',
			focus: true,
			'confirm-type': 'next',
			value: 'phone',
			hint: '手机号码必须是11位且必须符合号码规范',
			isHint: false,
		},
		{
			type: 'safe-password',
			placeholder: InputPlaceholderEnum.password,
			maxlength: inputPwdMaxLength,
			password: true,
			'placeholder-style': 'color: #636363;',
			'confirm-type': 'next',
			value: 'password',
			hint: '密码必须由数字字母或.组成6-18位',
			isHint: false,
		},
		{
			type: 'safe-password',
			placeholder: InputPlaceholderEnum.confirmPassword,
			maxlength: inputPwdMaxLength,
			password: true,
			'placeholder-style': 'color: #636363;',
			'confirm-type': 'done',
			value: 'confirmPassword',
			hint: '两次密码不一致',
			isHint: false,
		},
	]);

	// 授权选项
	const authorizationChecked = ref(false);
	const authorizationHandler = (value: boolean) => {
		authorizationChecked.value = value;
	};
	const changeAuthorization = () => {
		authorizationChecked.value = !authorizationChecked.value;
		console.log(authorizationChecked.value);
	};

	/** 手机号, 密码正则表达式 */
	const phoneReg = /^1[3-9][0-9]{9}$/,
		passwordReg = /^[\w.]{6,18}$/i;

	/**
	 * inputAstrict 限制input输入方法
	 * @param { KeyboardEvent } event - 键盘事件
	 * @param { InputPlaceholderEnum } target - 输入框的占位符
	 */
	const inputAstrict = (event: KeyboardEvent, target: string) => {
		const { key } = event;
		if (['Backspace'].includes(key)) return;

		// 只允许输入规定内容
		switch (target) {
			case InputPlaceholderEnum.phone:
				/[^0-9]/g.test(key) && event.preventDefault();

			case InputPlaceholderEnum.password:
			case InputPlaceholderEnum.confirmPassword:
				/[~！@#￥%……&*（）——+{}|：”》？《]/g.test(key) && event.preventDefault();

			default:
				// 禁止中文输入
				for (const key in loginStore.form) {
					(<any>loginStore.form)[key] = (<any>loginStore.form)[key].replace(/[\u4e00-\u9fa5]/gi, '');
				}
		}
	};

	/**
	 * 验证input内容
	 * @returns { boolean } - 如果都满足条件则返回true，否则false
	 */
	const inputVerify = (): boolean => {
		const { phone, password, confirmPassword } = loginStore.form;
		// 定义数组变量 (用于记录input是否符合规范)
		const distinguish = new Array(3).fill(false);
		const regFun = (reg: RegExp, target: InputListLoginInter, value: string) => {
			// 不符合
			if (!reg.test(value)) {
				target.isHint = true;
				return false;
			}
			// 符合
			else {
				target.isHint = false;
				return true;
			}
		};

		distinguish[0] = regFun(phoneReg, inputList[0], phone);
		distinguish[1] = regFun(passwordReg, inputList[1], password);
		// 两次密码是否一致
		if (password === confirmPassword) {
			inputList[2].isHint = false;
			distinguish[2] = true;
		} else {
			inputList[2].isHint = true;
			distinguish[2] = false;
		}

		return distinguish.every(item => item);
	};

	/** 验证手机号是否注册 */
	const phoneExist = async (): Promise<boolean> => {
		const result = await cellphoneCheck(loginStore.form.phone);
		console.log(result);
		if (result.exist !== 1) {
			uni.showToast({
				title: '该账号未注册',
				icon: 'none',
				mask: true,
				duration: 2000,
			});
			return true;
		}
		return false;
	};

	/** 注册处理器 */
	const registryHandler = debounce(async () => {
		// 验证input内容是否符合规范
		if (!inputVerify()) return;

		// 满足条件发送验证码
		const { phone } = loginStore.form;

		try {
			const captcha = await captchaSent({ phone });
			console.log(captcha);

			if (captcha.code !== 200) {
				uni.showToast({
					title: captcha.message,
					icon: 'none',
					mask: true,
				});
				return;
			}

			loginStore.changeDisplay('isValidateCode', true);
		} catch (error) {
			console.log('error:', error);
		}
	});

	/* 登录处理器 */
	const loginHandler = debounce(async () => {
		console.log(1);
		// 授权验证
		if (!authorizationChecked.value) {
			uni.showToast({
				title: '请先同意授权',
				icon: 'none',
				mask: false,
			});
			return;
		}

		// 验证手机号是否已经注册
		if (await phoneExist()) return;

		const { phone, password } = loginStore.form;

		const result = await loginCellphone({ phone, password });
		console.log(result);
		if (result.code !== 200) {
			uni.showToast({
				title: result.message,
				icon: 'none',
				mask: true
			});
			return;
		}
	}, 3000);

	return {
		loginStore,
		inputList,
		authorizationChecked,
		authorizationHandler,
		changeAuthorization,
		inputAstrict,
		loginHandler,
		registryHandler,
	};
}
